//
//  TSNoticeViewController.swift
//  TSProfitProject
//
//  Created by TMS on 2019/11/6.
//  Copyright © 2019 TMS. All rights reserved.
//

import UIKit

class TSNoticeViewController: TSBaseViewController {

    var tableController : TSBaseTableViewController!
    var dataSource : [TSNoticeModel] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        configViews()
        setupNavigationTitle(title: "公告")
        getDatas()
    }
    
}

extension TSNoticeViewController : UITableViewDelegate {
    
}

extension TSNoticeViewController : UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = tableView.dequeueReusableCell(withIdentifier: NSStringFromClass(TSNoticeTableViewCell.self)) as? TSNoticeTableViewCell
        
        if cell == nil {
            cell = TSNoticeTableViewCell.init(style: .default, reuseIdentifier: NSStringFromClass(TSNoticeTableViewCell.self))
        }
        
        cell?.setupCell(model: dataSource[indexPath.row])
        
        return cell!
    }
    
}

//MARK: - Network Request
extension TSNoticeViewController {
    
    func getDatas() {
        
        CBToast.showToastAction()
        TSNetworkManager.request(TMSNetworkTools.noticeData, showHUD: true, success: { (data) in

            CBToast.hiddenToastAction()
            self.dataSource.removeAll()
            let array = data as? Array<Dictionary<String, Any>>
            if array?.count ?? 0 > 0 {
                for item in array! {
                    let tempModel = TSNoticeModel.deserialize(from: item)
                    if let model = tempModel {
                        self.dataSource.append(model)
                    }
                }
            }
            self.tableController.tableView.reloadData()
        }) { (erroe) in
            
            CBToast.hiddenToastAction()
        }
        
    }

}

//MARK: - Initialize
extension TSNoticeViewController {
    
    func configViews() {
        
        tableController = TSBaseTableViewController(style: .plain)
        tableController.emptyAlertText = "暂无数据"
        tableController.tableView.backgroundColor = WHITE_COLOR
        tableController.tableView.delegate = self;
        tableController.tableView.dataSource = self
        tableController.tableView.separatorStyle = .none
        tableController.tableView.estimatedRowHeight = 100
        tableController.tableView.rowHeight = UITableView.automaticDimension
        self.view.addSubview(tableController.tableView)
        tableController.tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(T_NAVBARHEIGHT)
        }
    }
}
